<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class authJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        try {

            if (!$token = $request->token){
                return error('token缺失');
            }
            // 如果用户登陆后的所有请求没有jwt的token抛出异常

            if(!$user = JWTAuth::toUser($token)){
                return error('token失效');
            }

            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['user_not_found'], 404);
            }

        } catch (\Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return error('Token 无效');
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return error('Token 已过期');
            }else{
                return error('出错了');
            }
        }
        return $next($request);
    }
}
